<!DOCTYPE html>


  <html class="dark page-post">


<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="utf-8">
  
  <title>浅析redux-saga中间件及用法 | Poetry&#39;s Blog</title>

  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

  
    <meta name="keywords" content="Redux,中间件,">
  

  <meta name="description" content="一、redux-thunk1.1 redux的副作用处理 redux中的数据流大致是  UI—————&amp;gt;action（plain）—————&amp;gt;reducer——————&amp;gt;state——————&amp;gt;UI   redux是遵循函数式编程的规则，上述的数据流中，action是一个原始js对象（plain object）且reducer是一个纯函数，对于同步且没有副作用的操作，上述的">
<meta name="keywords" content="Redux,中间件">
<meta property="og:type" content="article">
<meta property="og:title" content="浅析redux-saga中间件及用法">
<meta property="og:url" content="http://blog.poetries.top/2018/08/29/redux-saga-and-redux-thunk/index.html">
<meta property="og:site_name" content="Poetry&#39;s Blog">
<meta property="og:description" content="一、redux-thunk1.1 redux的副作用处理 redux中的数据流大致是  UI—————&amp;gt;action（plain）—————&amp;gt;reducer——————&amp;gt;state——————&amp;gt;UI   redux是遵循函数式编程的规则，上述的数据流中，action是一个原始js对象（plain object）且reducer是一个纯函数，对于同步且没有副作用的操作，上述的">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="https://poetries1.gitee.io/img-repo/2019/10/484.png">
<meta property="og:image" content="https://poetries1.gitee.io/img-repo/2019/10/485.png">
<meta property="og:image" content="https://poetries1.gitee.io/img-repo/2019/10/486.png">
<meta property="og:image" content="https://poetries1.gitee.io/img-repo/2019/10/487.png">
<meta property="og:image" content="https://poetries1.gitee.io/img-repo/2019/10/488.png">
<meta property="og:image" content="https://poetries1.gitee.io/img-repo/2019/10/489.png">
<meta property="og:image" content="https://poetries1.gitee.io/img-repo/2019/10/490.png">
<meta property="og:image" content="https://poetries1.gitee.io/img-repo/2019/10/491.png">
<meta property="og:updated_time" content="2020-08-15T04:25:31.934Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="浅析redux-saga中间件及用法">
<meta name="twitter:description" content="一、redux-thunk1.1 redux的副作用处理 redux中的数据流大致是  UI—————&amp;gt;action（plain）—————&amp;gt;reducer——————&amp;gt;state——————&amp;gt;UI   redux是遵循函数式编程的规则，上述的数据流中，action是一个原始js对象（plain object）且reducer是一个纯函数，对于同步且没有副作用的操作，上述的">
<meta name="twitter:image" content="https://poetries1.gitee.io/img-repo/2019/10/484.png">

  

  
    <link rel="icon" href="/favicon.ico">
  

  <link href="/css/styles.css?v=c114cbeddx" rel="stylesheet">
<link href="/css/other.css?v=c114cbeddx" rel="stylesheet">


  
    <link rel="stylesheet" href="/css/personal-style.css">
  

  

  
  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "//hm.baidu.com/hm.js?40b1f89aa80f2527b3db779c6898c879";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>


  
  <script type="text/javascript">
	(function(){
	    var bp = document.createElement('script');
	    var curProtocol = window.location.protocol.split(':')[0];
	    if (curProtocol === 'https') {
	        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
	    }
	    else {
	        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
	    }
	    var s = document.getElementsByTagName("script")[0];
	    s.parentNode.insertBefore(bp, s);
	})();
  </script>



  
    <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
    <link rel="stylesheet" href="//cdn.bootcss.com/font-awesome/4.3.0/css/font-awesome.min.css">
  

  <!-- 聊天系统 -->
  
    
   <link type="text/css" rel="stylesheet" href="/renxi/default.css">
   <style>
      #modal {
        position: static !important;
      }
      .filter {
        width: 100%;
        height: 100%;
        position: absolute;
        top: 0;
        left: 0;
        background: #fe5757;
        animation: colorChange 30s ease-in-out infinite;
        animation-fill-mode: both;
        mix-blend-mode: overlay;
      }
  
      @keyframes colorChange {
        0%, 100% {
            opacity: 0;
        }
        50% {
            opacity: .9;
        }
      }
   </style>
</head>
</html>
<body>
  
  
    <span id="toolbox-mobile" class="toolbox-mobile">导航</span>
  

  <div class="post-header CENTER">
   
  <div class="toolbox">
    <a class="toolbox-entry" href="/">
      <span class="toolbox-entry-text">导航</span>
      <i class="icon-angle-down"></i>
      <i class="icon-home"></i>
    </a>
    <ul class="list-toolbox">
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/archives/"
            rel="noopener noreferrer"
            target="_self"
            >
            博客
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/categories/"
            rel="noopener noreferrer"
            target="_self"
            >
            分类
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/tags/"
            rel="noopener noreferrer"
            target="_self"
            >
            标签
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/search/"
            rel="noopener noreferrer"
            target="_self"
            >
            搜索
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/link/"
            rel="noopener noreferrer"
            target="_self"
            >
            友链
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/about/"
            rel="noopener noreferrer"
            target="_self"
            >
            关于
          </a>
        </li>
      
    </ul>
  </div>


</div>


  <div id="toc" class="toc-article">
    <strong class="toc-title">文章目录<i class="iconfont toc-title" style="display:inline-block;color:#87998d;width:20px;height:20px;">&#xf004b;</i></strong>
    <ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#一、redux-thunk"><span class="toc-text">一、redux-thunk</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#1-1-redux的副作用处理"><span class="toc-text">1.1 redux的副作用处理</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#1-2-redux-thunk源码"><span class="toc-text">1.2 redux-thunk源码</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#1-3-redux-thunk的缺点"><span class="toc-text">1.3 redux-thunk的缺点</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#二、redux-saga-简介"><span class="toc-text">二、redux-saga 简介</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#三、redux-saga使用案例"><span class="toc-text">三、redux-saga使用案例</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#四、redux-saga使用细节"><span class="toc-text">四、redux-saga使用细节</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#4-1-声明式的Effect"><span class="toc-text">4.1 声明式的Effect</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#4-2-Effect提供的具体方法"><span class="toc-text">4.2 Effect提供的具体方法</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#4-2-1-take"><span class="toc-text">4.2.1 take</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#4-2-2-call-apply"><span class="toc-text">4.2.2 call(apply)</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#4-2-3-put"><span class="toc-text">4.2.3 put</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#4-2-4-select"><span class="toc-text">4.2.4 select</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#4-2-5-fork"><span class="toc-text">4.2.5 fork</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#4-2-6-takeEvery和takeLatest"><span class="toc-text">4.2.6 takeEvery和takeLatest</span></a></li></ol></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#五、案例分析一"><span class="toc-text">五、案例分析一</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#5-1-LoginPanel-登陆页"><span class="toc-text">5.1 LoginPanel(登陆页)</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#5-2-LoginSuccess"><span class="toc-text">5.2 LoginSuccess</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#六、案例分析二"><span class="toc-text">六、案例分析二</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#6-1-配置saga信息"><span class="toc-text">6.1 配置saga信息</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#6-2-配置reduce"><span class="toc-text">6.2 配置reduce</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#6-3-处理action"><span class="toc-text">6.3 处理action</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#6-4-处理sagas"><span class="toc-text">6.4 处理sagas</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#七、总结"><span class="toc-text">七、总结</span></a></li></ol>
  </div>
  




<div class="content content-post CENTER">
   <!-- canvas 彩带 -->
<canvas id="evanyou" width="1302" height="678" style="position: fixed;width: 100%;height: 100%;top: 0;left:0;z-index:-1;"></canvas>

<article id="post-redux-saga-and-redux-thunk" class="article article-type-post" itemprop="blogPost">
  <header class="article-header" style="position:relative;">
    <h1 class="post-title">浅析redux-saga中间件及用法</h1>

    <div class="article-meta">
      <span>
        <i class="icon-calendar"></i>
        <span>2018.08.29</span>
      </span>

      
        <span class="article-author">
          <i class="icon-user"></i>
          <span>Poetry</span>
        </span>
      

      
  <span class="article-category">
    <i class="icon-list"></i>
    <a class="article-category-link" href="/categories/Front-End/">Front-End</a>
  </span>



      

      
      <i class="fa fa-eye"></i> 
        <span id="busuanzi_container_page_pv">
           &nbsp热度 <span id="busuanzi_value_page_pv">
           <i class="fa fa-spinner fa-spin"></i></span>℃
        </span>
      
      
       
          <span class="post-count">
            <i class="fa fa-file-word-o"></i>&nbsp
            <span>字数统计 3.7k字</span>
          </span>

          <span class="post-count">
            <i class="fa fa-columns"></i>&nbsp
            <span>阅读时长 16分</span>
          </span>
      
      
    </div>

    <i class="iconfont" id="toc-eye" style="display:inline-block;color:#b36619;position:absolute;top:0;right:0;cursor:pointer;
    font-size: 24px;">&#xe61c;</i>

  </header>

  <div class="article-content">
    
      <div id="container">
        <h2 id="一、redux-thunk"><a href="#一、redux-thunk" class="headerlink" title="一、redux-thunk"></a>一、redux-thunk</h2><h3 id="1-1-redux的副作用处理"><a href="#1-1-redux的副作用处理" class="headerlink" title="1.1 redux的副作用处理"></a>1.1 redux的副作用处理</h3><blockquote>
<p>redux中的数据流大致是</p>
</blockquote>
<figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">UI—————&gt;action（plain）—————&gt;reducer——————&gt;state——————&gt;UI</span><br></pre></td></tr></table></figure>
<p><img src="https://poetries1.gitee.io/img-repo/2019/10/484.png" alt></p>
<ul>
<li><code>redux</code>是遵循函数式编程的规则，上述的数据流中，<code>action</code>是一个原始js对象（<code>plain object</code>）且<code>reducer</code>是一个纯函数，对于同步且没有副作用的操作，上述的数据流起到可以管理数据，从而控制视图层更新的目的</li>
<li>如果存在副作用函数，那么我们需要首先处理副作用函数，然后生成原始的js对象。如何处理副作用操作，在<code>redux</code>中选择在发出<code>action</code>，到<code>reducer</code>处理函数之间使用中间件处理副作用</li>
</ul>
<blockquote>
<p>redux增加中间件处理副作用后的数据流大致如下：</p>
</blockquote>
<figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">UI——&gt;action(side function)—&gt;middleware—&gt;action(plain)—&gt;reducer—&gt;state—&gt;UI</span><br></pre></td></tr></table></figure>
<p><img src="https://poetries1.gitee.io/img-repo/2019/10/485.png" alt></p>
<blockquote>
<p>在有副作用的<code>action</code>和原始的<code>action</code>之间增加中间件处理，从图中我们也可以看出，中间件的作用就是：</p>
</blockquote>
<ul>
<li>转换异步操作，<strong>生成原始的action</strong>，这样，<code>reducer</code>函数就能处理相应的<code>action</code>，从而改变<code>state</code>，更新<code>UI</code></li>
</ul>
<h3 id="1-2-redux-thunk源码"><a href="#1-2-redux-thunk源码" class="headerlink" title="1.2 redux-thunk源码"></a>1.2 redux-thunk源码</h3><blockquote>
<p>在redux中，thunk是redux作者给出的中间件，实现极为简单，10多行代码</p>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">createThunkMiddleware</span>(<span class="params">extraArgument</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">return</span> <span class="function">(<span class="params">&#123; dispatch, getState &#125;</span>) =&gt;</span> <span class="function"><span class="params">next</span> =&gt;</span> <span class="function"><span class="params">action</span> =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">typeof</span> action === <span class="string">'function'</span>) &#123;</span><br><span class="line">      <span class="keyword">return</span> action(dispatch, getState, extraArgument);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> next(action);</span><br><span class="line">  &#125;;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> thunk = createThunkMiddleware();</span><br><span class="line">thunk.withExtraArgument = createThunkMiddleware;</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> thunk;</span><br></pre></td></tr></table></figure>
<blockquote>
<p>这几行代码做的事情也很简单，判别action的类型，如果action是函数，就调用这个函数，调用的步骤为</p>
</blockquote>
<figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">action(dispatch, getState, extraArgument);</span><br></pre></td></tr></table></figure>
<blockquote>
<p>发现实参为<code>dispatch</code>和<code>getState</code>，因此我们在定义<code>action</code>为<code>thunk</code>函数是，一般形参为<code>dispatch</code>和<code>getState</code></p>
</blockquote>
<h3 id="1-3-redux-thunk的缺点"><a href="#1-3-redux-thunk的缺点" class="headerlink" title="1.3 redux-thunk的缺点"></a>1.3 redux-thunk的缺点</h3><blockquote>
<p><code>thunk</code>的缺点也是很明显的，<code>thunk</code>仅仅做了执行这个函数，并不在乎函数主体内是什么，也就是说<code>thunk</code>使得<code>redux</code>可以接受函数作为<code>action</code>，但是函数的内部可以多种多样。比如下面是一个获取商品列表的异步操作所对应的<code>action</code></p>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> ()=&gt;<span class="function">(<span class="params">dispatch</span>)=&gt;</span>&#123;</span><br><span class="line">    fetch(<span class="string">'/api/goodList'</span>,&#123; <span class="comment">//fecth返回的是一个promise</span></span><br><span class="line">      method: <span class="string">'get'</span>,</span><br><span class="line">      dataType: <span class="string">'json'</span>,</span><br><span class="line">    &#125;).then(<span class="function"><span class="keyword">function</span>(<span class="params">json</span>)</span>&#123;</span><br><span class="line">      <span class="keyword">var</span> json=<span class="built_in">JSON</span>.parse(json);</span><br><span class="line">      <span class="keyword">if</span>(json.msg==<span class="number">200</span>)&#123;</span><br><span class="line">        dispatch(&#123;<span class="attr">type</span>:<span class="string">'init'</span>,<span class="attr">data</span>:json.data&#125;);</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;,<span class="function"><span class="keyword">function</span>(<span class="params">error</span>)</span>&#123;</span><br><span class="line">      <span class="built_in">console</span>.log(error);</span><br><span class="line">    &#125;);</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>
<blockquote>
<p>从这个具有副作用的<code>action</code>中，我们可以看出，函数内部极为复杂。如果需要为每一个异步操作都如此定义一个<code>action</code>，显然<code>action</code>不易维护</p>
</blockquote>
<p><strong>action不易维护的原因</strong></p>
<ul>
<li><code>action</code>的形式不统一</li>
<li>就是异步操作太为分散，分散在了各个<code>action</code>中</li>
</ul>
<h2 id="二、redux-saga-简介"><a href="#二、redux-saga-简介" class="headerlink" title="二、redux-saga 简介"></a>二、redux-saga 简介</h2><blockquote>
<p><code>redux-saga</code>是一个 <code>redux</code>中间件，它具有如下特性</p>
</blockquote>
<ul>
<li>集中处理 <code>redux</code> 副作用问题。</li>
<li>被实现为 <code>generator</code> 。</li>
<li>类 <code>redux-thunk</code> 中间件。</li>
<li><code>watch</code>/<code>worker</code>（监听-&gt;执行） 的工作形式</li>
</ul>
<p><strong>redux-saga的优点</strong></p>
<ul>
<li>集中处理了所有的异步操作，异步接口部分一目了然</li>
<li><code>action</code>是普通对象，这跟<code>redux</code>同步的<code>action</code>一模一样</li>
<li>通过<code>Effect</code>，方便异步接口的测试</li>
<li>通过<code>worker</code> 和<code>watcher</code>可以实现非阻塞异步调用，并且同时可以实现非阻塞调用下的事件监听</li>
<li>异步操作的流程是可以控制的，可以随时取消相应的异步操作</li>
</ul>
<blockquote>
<p>基本用法</p>
</blockquote>
<ul>
<li>使用<code>createSagaMiddleware</code>方法创建<code>saga</code> 的<code>Middleware</code>，然后在创建的<code>redux</code>的<code>store</code>时，使用<code>applyMiddleware</code>函数将创建的<code>saga Middleware</code>实例绑定到<code>store</code>上，最后可以调用<code>saga Middleware</code>的<code>run</code>函数来执行某个或者某些<code>Middleware</code>。</li>
<li>在<code>saga</code>的<code>Middleware</code>中，可以使用<code>takeEvery</code>或者<code>takeLatest</code>等<code>API</code>来监听某个<code>action</code>，当某个<code>action</code>触发后，<code>saga</code>可以使用<code>call</code>发起异步操作，操作完成后使用<code>put</code>函数触发<code>action</code>，同步更新<code>state</code>，从而完成整个<code>State</code>的更新。</li>
</ul>
<h2 id="三、redux-saga使用案例"><a href="#三、redux-saga使用案例" class="headerlink" title="三、redux-saga使用案例"></a>三、redux-saga使用案例</h2><ul>
<li><code>redux-saga</code>是控制执行的<code>generator</code>，在<code>redux-saga</code>中<code>action</code>是原始的<code>js</code>对象，把所有的异步副作用操作放在了<code>saga</code>函数里面。这样既统一了<code>action</code>的形式，又使得异步操作集中可以被集中处理</li>
<li><code>redux-saga</code>是通过<code>genetator</code>实现的，如果不支持<code>generator</code>需要通过插件<code>babel-polyfill</code>转义。我们接着来实现一个输出<code>hellosaga</code>的例子</li>
</ul>
<p><strong>创建一个helloSaga.js文件</strong></p>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">export</span> <span class="function"><span class="keyword">function</span> * <span class="title">helloSaga</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">'Hello Sagas!'</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><strong>在redux中使用redux-saga中间件</strong></p>
<blockquote>
<p>在<code>main.js</code>中</p>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> &#123; createStore, applyMiddleware &#125; <span class="keyword">from</span> <span class="string">'redux'</span></span><br><span class="line"><span class="keyword">import</span> createSagaMiddleware <span class="keyword">from</span> <span class="string">'redux-saga'</span></span><br><span class="line"><span class="keyword">import</span> &#123; helloSaga &#125; <span class="keyword">from</span> <span class="string">'./sagas'</span></span><br><span class="line"><span class="keyword">const</span> sagaMiddleware=createSagaMiddleware();</span><br><span class="line"><span class="keyword">const</span> store = createStore(</span><br><span class="line"> reducer,</span><br><span class="line"> applyMiddleware(sagaMiddleware)</span><br><span class="line">);</span><br><span class="line">sagaMiddleware.run(helloSaga);</span><br><span class="line"><span class="comment">//会输出Hello, Sagas!</span></span><br></pre></td></tr></table></figure>
<blockquote>
<p>和调用<code>redux</code>的其他中间件一样，如果想使用<code>redux-saga</code>中间件，那么只要在<code>applyMiddleware</code>中调用一个<code>createSagaMiddleware</code>的实例。唯一不同的是需要调用<code>run</code>方法使得<code>generator</code>可以开始执行</p>
</blockquote>
<h2 id="四、redux-saga使用细节"><a href="#四、redux-saga使用细节" class="headerlink" title="四、redux-saga使用细节"></a>四、redux-saga使用细节</h2><h3 id="4-1-声明式的Effect"><a href="#4-1-声明式的Effect" class="headerlink" title="4.1 声明式的Effect"></a>4.1 声明式的Effect</h3><blockquote>
<p>在<code>redux-saga</code>中提供了一系列的<code>api</code>，比如<code>take</code>、<code>put</code>、<code>all</code>、<code>select</code>等<code>API</code>，在<code>redux-saga</code>中将这一系列的<code>api</code>都定义为Effect。这些<code>Effect</code>执行后，当函数<code>resolve</code>时返回一个描述对象，然后<code>redux-saga</code>中间件根据这个描述对象恢复执行<code>generator</code>中的函数</p>
</blockquote>
<p><strong>redux-thunk的大体过程</strong></p>
<blockquote>
<p><code>action1(side function)</code>—&gt;<code>redux-thunk</code>监听—&gt;执行相应的有副作用的方法—&gt;<code>action2(plain object)</code></p>
</blockquote>
<p><img src="https://poetries1.gitee.io/img-repo/2019/10/486.png" alt></p>
<blockquote>
<p>转化到<code>action2</code>是一个原始<code>js</code>对象形式的<code>action</code>，然后执行<code>reducer</code>函数就会更新<code>store</code>中的<code>state</code></p>
</blockquote>
<p><strong>redux-saga的大体过程</strong></p>
<blockquote>
<p>action1(plain object)——&gt;redux-saga监听—&gt;执行相应的Effect方法——&gt;返回描述对象—&gt;恢复执行异步和副作用函数—&gt;action2(plain object)</p>
</blockquote>
<p><img src="https://poetries1.gitee.io/img-repo/2019/10/487.png" alt></p>
<blockquote>
<p>对比<code>redux-thunk</code>我们发现，<code>redux-saga</code>中监听到了原始<code>js</code>对象<code>action</code>，并不会马上执行副作用操作，会先通过<code>Effect</code>方法将其转化成一个描述对象，然后再将描述对象，作为标识，再恢复执行副作用函数</p>
</blockquote>
<h3 id="4-2-Effect提供的具体方法"><a href="#4-2-Effect提供的具体方法" class="headerlink" title="4.2 Effect提供的具体方法"></a>4.2 Effect提供的具体方法</h3><blockquote>
<p>下面来介绍几个<code>Effect</code>中常用的几个方法，从低阶的API，比如<code>take</code>，<code>call(apply)</code>，<code>fork</code>，<code>put</code>，<code>select</code>等，以及高阶<code>API</code>，比如<code>takeEvery</code>和<code>takeLatest</code>等</p>
</blockquote>
<figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">import &#123;take,call,put,select,fork,takeEvery,takeLatest&#125; from &apos;redux-saga/effects&apos;</span><br></pre></td></tr></table></figure>
<h4 id="4-2-1-take"><a href="#4-2-1-take" class="headerlink" title="4.2.1 take"></a>4.2.1 take</h4><blockquote>
<p><code>take</code>这个方法，是用来监听<code>action</code>，返回的是监听到的<code>action</code>对象。比如</p>
</blockquote>
<figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">const loginAction = &#123;</span><br><span class="line">   type:&apos;login&apos;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<blockquote>
<p>在<code>UI Component</code>中<code>dispatch</code>一个<code>action</code></p>
</blockquote>
<figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">dispatch(loginAction)</span><br></pre></td></tr></table></figure>
<p>在saga中使用：</p>
<figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">const action = yield take(&apos;login&apos;);</span><br></pre></td></tr></table></figure>
<blockquote>
<p>可以监听到UI传递到中间件的<code>Action</code>,上述<code>take</code>方法的返回，就是<code>dipath</code>的原始对象。一旦监听到<code>login</code>动作，返回的<code>action</code>为：</p>
</blockquote>
<figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">&#123;</span><br><span class="line">  type:&apos;login&apos;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="4-2-2-call-apply"><a href="#4-2-2-call-apply" class="headerlink" title="4.2.2 call(apply)"></a>4.2.2 call(apply)</h4><blockquote>
<p><code>call</code>和<code>apply</code>方法与<code>js</code>中的<code>call</code>和<code>apply</code>相似，我们以<code>call</code>方法为例</p>
</blockquote>
<figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">call(fn, ...args)</span><br></pre></td></tr></table></figure>
<blockquote>
<p><code>call</code>方法调用<code>fn</code>，参数为<code>args</code>，返回一个描述对象。不过这里<code>call</code>方法传入的函数<code>fn</code>可以是普通函数，也可以是<code>generator</code>。<code>call</code>方法应用很广泛，在<code>redux-saga</code>中使用异步请求等常用<code>call</code>方法来实现</p>
</blockquote>
<figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">yield call(fetch,&apos;/userInfo&apos;,username)</span><br></pre></td></tr></table></figure>
<h4 id="4-2-3-put"><a href="#4-2-3-put" class="headerlink" title="4.2.3 put"></a>4.2.3 put</h4><blockquote>
<p>redux-saga做为中间件，工作流是这样的</p>
</blockquote>
<figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">UI——&gt;action1————&gt;redux-saga中间件————&gt;action2————&gt;reducer..</span><br></pre></td></tr></table></figure>
<blockquote>
<p>从工作流中，我们发现<code>redux-saga</code>执行完副作用函数后，必须发出<code>action</code>，然后这个<code>action</code>被<code>reducer</code>监听，从而达到更新<code>state</code>的目的。相应的这里的<code>put</code>对应与<code>redux</code>中的<code>dispatch</code>，工作流程图如下</p>
</blockquote>
<p><img src="https://poetries1.gitee.io/img-repo/2019/10/488.png" alt></p>
<blockquote>
<p>可以看出<code>redux-saga</code>执行副作用方法转化<code>action</code>时，<code>put</code>这个<code>Effect</code>方法跟<code>redux</code>原始的<code>dispatch</code>相似，都是可以发出<code>action</code>，且发出的<code>action</code>都会被<code>reducer</code>监听到。<code>put</code>的使用方法</p>
</blockquote>
<figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">yield put(&#123;type:&apos;login&apos;&#125;)</span><br></pre></td></tr></table></figure>
<h4 id="4-2-4-select"><a href="#4-2-4-select" class="headerlink" title="4.2.4 select"></a>4.2.4 select</h4><blockquote>
<p><code>put</code>方法与<code>redux</code>中的<code>dispatch</code>相对应，同样的如果我们想在中间件中获取<code>state</code>，那么需要使用<code>select</code>。<code>select</code>方法对应的是<code>redux</code>中的<code>getState</code>，用户获取<code>store</code>中的<code>state</code>，使用方法：</p>
</blockquote>
 <figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">const id = yield select(state =&gt; state.id);</span><br></pre></td></tr></table></figure>
<h4 id="4-2-5-fork"><a href="#4-2-5-fork" class="headerlink" title="4.2.5 fork"></a>4.2.5 fork</h4><blockquote>
<p><code>fork</code>方法相当于<code>web work</code>，<code>fork</code>方法不会阻塞主线程，在非阻塞调用中十分有用</p>
</blockquote>
<h4 id="4-2-6-takeEvery和takeLatest"><a href="#4-2-6-takeEvery和takeLatest" class="headerlink" title="4.2.6 takeEvery和takeLatest"></a>4.2.6 takeEvery和takeLatest</h4><blockquote>
<p><code>takeEvery</code>和<code>takeLatest</code>用于监听相应的动作并执行相应的方法，是构建在<code>take</code>和<code>fork</code>上面的高阶<code>api</code>，比如要监听<code>login</code>动作，好用<code>takeEvery</code>方法可以</p>
</blockquote>
 <figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">takeEvery(&apos;login&apos;,loginFunc)</span><br></pre></td></tr></table></figure>
<ul>
<li><code>takeEvery</code>监听到<code>login</code>的动作，就会执行<code>loginFunc</code>方法，除此之外，<code>takeEvery</code>可以同时监听到多个相同的<code>action</code>。</li>
<li><code>takeLatest</code>方法跟<code>takeEvery</code>是相同方式调用</li>
</ul>
<figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">takeLatest(&apos;login&apos;,loginFunc)</span><br></pre></td></tr></table></figure>
<blockquote>
<p>与<code>takeLatest</code>不同的是，<code>takeLatest</code>是会监听执行最近的那个被触发的<code>action</code></p>
</blockquote>
<h2 id="五、案例分析一"><a href="#五、案例分析一" class="headerlink" title="五、案例分析一"></a>五、案例分析一</h2><blockquote>
<p>接着我们来实现一个<code>redux-saga</code>样例，存在一个登陆页，登陆成功后，显示列表页，并且，在列表页，可以点击登出，返回到登陆页。例子的最终展示效果如下</p>
</blockquote>
<p><img src="https://poetries1.gitee.io/img-repo/2019/10/489.png" alt></p>
<blockquote>
<p>样例的功能流程图为</p>
</blockquote>
<p><img src="https://poetries1.gitee.io/img-repo/2019/10/490.png" alt></p>
<h3 id="5-1-LoginPanel-登陆页"><a href="#5-1-LoginPanel-登陆页" class="headerlink" title="5.1 LoginPanel(登陆页)"></a>5.1 LoginPanel(登陆页)</h3><p><strong>输入时时保存用户名和密码</strong></p>
<ul>
<li>用户名输入框和密码框onchange时触发的函数为</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line">changeUsername:<span class="function">(<span class="params">e</span>)=&gt;</span>&#123;</span><br><span class="line">    dispatch(&#123;<span class="attr">type</span>:<span class="string">'CHANGE_USERNAME'</span>,<span class="attr">value</span>:e.target.value&#125;);</span><br><span class="line"> &#125;,</span><br><span class="line">changePassword:<span class="function">(<span class="params">e</span>)=&gt;</span>&#123;</span><br><span class="line">  dispatch(&#123;<span class="attr">type</span>:<span class="string">'CHANGE_PASSWORD'</span>,<span class="attr">value</span>:e.target.value&#125;);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<blockquote>
<p>在函数中最后会<code>dispatch</code>两个<code>action：CHANGE_USERNAME和CHANGE_PASSWORD</code></p>
</blockquote>
<ul>
<li>在<code>saga.js</code>文件中监听这两个方法并执行副作用函数，最后<code>put</code>发出转化后的<code>action</code>，给<code>reducer</code>函数调用</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> * <span class="title">watchUsername</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">  <span class="keyword">while</span>(<span class="literal">true</span>)&#123;</span><br><span class="line">    <span class="keyword">const</span> action= <span class="keyword">yield</span> take(<span class="string">'CHANGE_USERNAME'</span>);</span><br><span class="line">    <span class="keyword">yield</span> put(&#123;<span class="attr">type</span>:<span class="string">'change_username'</span>,</span><br><span class="line">    value:action.value&#125;);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">function</span> * <span class="title">watchPassword</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">  <span class="keyword">while</span>(<span class="literal">true</span>)&#123;</span><br><span class="line">    <span class="keyword">const</span> action=<span class="keyword">yield</span> take(<span class="string">'CHANGE_PASSWORD'</span>);</span><br><span class="line">    <span class="keyword">yield</span> put(&#123;<span class="attr">type</span>:<span class="string">'change_password'</span>,</span><br><span class="line">    value:action.value&#125;);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<blockquote>
<p>最后在<code>reducer</code>中接收到<code>redux-saga</code>的<code>put</code>方法传递过来的<code>action：change_username</code>和<code>change_password</code>，然后更新<code>state</code></p>
</blockquote>
<p><strong>监听登陆事件判断登陆是否成功</strong></p>
<blockquote>
<p>在UI中发出的登陆事件为</p>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line">toLoginIn:<span class="function">(<span class="params">username,password</span>)=&gt;</span>&#123;</span><br><span class="line">  dispatch(&#123;<span class="attr">type</span>:<span class="string">'TO_LOGIN_IN'</span>,username,password&#125;);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<blockquote>
<p>登陆事件的<code>action</code>为：<code>TO_LOGIN_IN</code>.对于登入事件的处理函数为：</p>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">while</span>(<span class="literal">true</span>)&#123;</span><br><span class="line">    <span class="comment">//监听登入事件</span></span><br><span class="line">    <span class="keyword">const</span> action1=<span class="keyword">yield</span> take(<span class="string">'TO_LOGIN_IN'</span>);</span><br><span class="line">    <span class="keyword">const</span> res=<span class="keyword">yield</span> call(fetchSmart,<span class="string">'/login'</span>,&#123;</span><br><span class="line">      method:<span class="string">'POST'</span>,</span><br><span class="line">      body:<span class="built_in">JSON</span>.stringify(&#123;</span><br><span class="line">        username:action1.username,</span><br><span class="line">        password:action1.password</span><br><span class="line">    &#125;)</span><br><span class="line">    <span class="keyword">if</span>(res)&#123;</span><br><span class="line">      put(&#123;<span class="attr">type</span>:<span class="string">'to_login_in'</span>&#125;);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<blockquote>
<p>在上述的处理函数中，首先监听原始动作提取出传递来的用户名和密码，然后请求是否登陆成功，如果登陆成功有返回值，则执行<code>put</code>的<code>action:to_login_in</code></p>
</blockquote>
<h3 id="5-2-LoginSuccess"><a href="#5-2-LoginSuccess" class="headerlink" title="5.2 LoginSuccess"></a>5.2 LoginSuccess</h3><blockquote>
<p>(登陆成功列表展示页)</p>
</blockquote>
<ul>
<li>登陆成功后的页面功能包括：<ul>
<li>获取列表信息，展示列表信息</li>
<li>登出功能，点击可以返回登陆页面</li>
</ul>
</li>
</ul>
<p><strong>获取列表信息</strong></p>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> &#123;delay&#125; <span class="keyword">from</span> <span class="string">'redux-saga'</span>;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> * <span class="title">getList</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">  <span class="keyword">try</span> &#123;</span><br><span class="line">   <span class="keyword">yield</span> delay(<span class="number">3000</span>);</span><br><span class="line">   <span class="keyword">const</span> res = <span class="keyword">yield</span> call(fetchSmart,<span class="string">'/list'</span>,&#123;</span><br><span class="line">     method:<span class="string">'POST'</span>,</span><br><span class="line">     body:<span class="built_in">JSON</span>.stringify(&#123;&#125;)</span><br><span class="line">   &#125;);</span><br><span class="line">   <span class="keyword">yield</span> put(&#123;<span class="attr">type</span>:<span class="string">'update_list'</span>,<span class="attr">list</span>:res.data.activityList&#125;);</span><br><span class="line"> &#125; <span class="keyword">catch</span>(error) &#123;</span><br><span class="line">   <span class="keyword">yield</span> put(&#123;<span class="attr">type</span>:<span class="string">'update_list_error'</span>, error&#125;);</span><br><span class="line"> &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<blockquote>
<p>为了演示请求过程，我们在本地<code>mock</code>，通过<code>redux-saga</code>的工具函数<code>delay</code>，<code>delay</code>的功能相当于延迟xx秒，因为真实的请求存在延迟，因此可以用delay在本地模拟真实场景下的请求延迟</p>
</blockquote>
<p><strong>登出功能</strong></p>
<figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">const action2=yield take(&apos;TO_LOGIN_OUT&apos;);</span><br><span class="line">yield put(&#123;type:&apos;to_login_out&apos;&#125;);</span><br></pre></td></tr></table></figure>
<blockquote>
<p>与登入相似，登出的功能从UI处接受<code>action:TO_LOGIN_OUT</code>,然后转发<code>action:to_login_out</code></p>
</blockquote>
<p><strong>完整的实现登入登出和列表展示的代码</strong></p>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> * <span class="title">getList</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">  <span class="keyword">try</span> &#123;</span><br><span class="line">   <span class="keyword">yield</span> delay(<span class="number">3000</span>);</span><br><span class="line">   <span class="keyword">const</span> res = <span class="keyword">yield</span> call(fetchSmart,<span class="string">'/list'</span>,&#123;</span><br><span class="line">     method:<span class="string">'POST'</span>,</span><br><span class="line">     body:<span class="built_in">JSON</span>.stringify(&#123;&#125;)</span><br><span class="line">   &#125;);</span><br><span class="line">   <span class="keyword">yield</span> put(&#123;<span class="attr">type</span>:<span class="string">'update_list'</span>,<span class="attr">list</span>:res.data.activityList&#125;);</span><br><span class="line"> &#125; <span class="keyword">catch</span>(error) &#123;</span><br><span class="line">   <span class="keyword">yield</span> put(&#123;<span class="attr">type</span>:<span class="string">'update_list_error'</span>, error&#125;);</span><br><span class="line"> &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> * <span class="title">watchIsLogin</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">  <span class="keyword">while</span>(<span class="literal">true</span>)&#123;</span><br><span class="line">    <span class="comment">//监听登入事件</span></span><br><span class="line">    <span class="keyword">const</span> action1=<span class="keyword">yield</span> take(<span class="string">'TO_LOGIN_IN'</span>);</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">const</span> res=<span class="keyword">yield</span> call(fetchSmart,<span class="string">'/login'</span>,&#123;</span><br><span class="line">      method:<span class="string">'POST'</span>,</span><br><span class="line">      body:<span class="built_in">JSON</span>.stringify(&#123;</span><br><span class="line">        username:action1.username,</span><br><span class="line">        password:action1.password</span><br><span class="line">      &#125;)</span><br><span class="line">    &#125;);</span><br><span class="line">    </span><br><span class="line">    <span class="comment">//根据返回的状态码判断登陆是否成功</span></span><br><span class="line">    <span class="keyword">if</span>(res.status===<span class="number">10000</span>)&#123;</span><br><span class="line">      <span class="keyword">yield</span> put(&#123;<span class="attr">type</span>:<span class="string">'to_login_in'</span>&#125;);</span><br><span class="line">      <span class="comment">//登陆成功后获取首页的活动列表</span></span><br><span class="line">      <span class="keyword">yield</span> call(getList);</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="comment">//监听登出事件</span></span><br><span class="line">    <span class="keyword">const</span> action2=<span class="keyword">yield</span> take(<span class="string">'TO_LOGIN_OUT'</span>);</span><br><span class="line">    <span class="keyword">yield</span> put(&#123;<span class="attr">type</span>:<span class="string">'to_login_out'</span>&#125;);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<blockquote>
<p>通过请求状态码判断登入是否成功，在登陆成功后，可以通过</p>
</blockquote>
<figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">yield call(getList)</span><br></pre></td></tr></table></figure>
<blockquote>
<p>注意call方法调用是会阻塞主线程的，具体来说</p>
</blockquote>
<ul>
<li>在call方法调用结束之前，call方法之后的语句是无法执行的</li>
<li>如果<code>call(getList)</code>存在延迟，<code>call(getList)</code>之后的语句 <code>const action2=yieldtake(&#39;TO_LOGIN_OUT&#39;)</code>在<code>call</code>方法返回结果之前无法执行</li>
<li>在延迟期间的登出操作会被忽略</li>
</ul>
<p><img src="https://poetries1.gitee.io/img-repo/2019/10/491.png" alt></p>
<p><strong>无阻塞调用</strong></p>
<figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">yield call(getList)</span><br></pre></td></tr></table></figure>
<p>修改为</p>
<figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">yield fork(getList)</span><br></pre></td></tr></table></figure>
<blockquote>
<p>通过fork方法不会阻塞主线程，在白屏时点击登出，可以立刻响应登出功能，从而返回登陆页面</p>
</blockquote>
<h2 id="六、案例分析二"><a href="#六、案例分析二" class="headerlink" title="六、案例分析二"></a>六、案例分析二</h2><h3 id="6-1-配置saga信息"><a href="#6-1-配置saga信息" class="headerlink" title="6.1 配置saga信息"></a>6.1 配置saga信息</h3><blockquote>
<p><code>src/store/configureStore.js</code></p>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> &#123; createStore, applyMiddleware, compose &#125; <span class="keyword">from</span> <span class="string">'redux'</span></span><br><span class="line"><span class="comment">// import &#123;createLogger &#125; from 'redux-logger'</span></span><br><span class="line"><span class="keyword">import</span> createHistory <span class="keyword">from</span> <span class="string">'history/createBrowserHistory'</span></span><br><span class="line"><span class="keyword">import</span> createSagaMiddleware <span class="keyword">from</span> <span class="string">'redux-saga'</span>;</span><br><span class="line"><span class="keyword">import</span> &#123; routerMiddleware &#125; <span class="keyword">from</span> <span class="string">'react-router-redux'</span></span><br><span class="line"><span class="keyword">import</span> rootSaga <span class="keyword">from</span> <span class="string">'../sagas'</span></span><br><span class="line"><span class="keyword">import</span> rootReducer <span class="keyword">from</span> <span class="string">'../reducers/'</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">const</span> history = createHistory()</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> middleware = routerMiddleware(history)</span><br><span class="line"></span><br><span class="line"><span class="comment">//创建saga middleware</span></span><br><span class="line"><span class="keyword">const</span> sagaMiddleware = createSagaMiddleware();</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> configureStore = <span class="function"><span class="params">preloadedState</span> =&gt;</span> &#123;</span><br><span class="line">	<span class="comment">// 安装 Redux-DevTools Chrome 插件后可用 composeEnhancers()</span></span><br><span class="line">	<span class="keyword">const</span> composeEnhancers = <span class="built_in">window</span>.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose</span><br><span class="line"></span><br><span class="line">	<span class="keyword">const</span> store = createStore(</span><br><span class="line">		rootReducer,</span><br><span class="line">		preloadedState,</span><br><span class="line">		composeEnhancers(</span><br><span class="line">			applyMiddleware(sagaMiddleware,middleware)</span><br><span class="line">		)</span><br><span class="line">	)</span><br><span class="line">	sagaMiddleware.run(rootSaga);</span><br><span class="line">	<span class="keyword">if</span> (<span class="built_in">module</span>.hot) &#123;</span><br><span class="line">		<span class="comment">// Enable Webpack hot module replacement for reducers</span></span><br><span class="line">		<span class="built_in">module</span>.hot.accept(<span class="string">'../reducers'</span>, () =&gt; &#123;</span><br><span class="line">			<span class="keyword">const</span> nextRootReducer = <span class="built_in">require</span>(<span class="string">'../reducers'</span>).default</span><br><span class="line">			store.replaceReducer(nextRootReducer)</span><br><span class="line">		&#125;)</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="keyword">return</span> store</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> configureStore</span><br></pre></td></tr></table></figure>
<h3 id="6-2-配置reduce"><a href="#6-2-配置reduce" class="headerlink" title="6.2 配置reduce"></a>6.2 配置reduce</h3><figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="comment">// src/reducers/index.js</span></span><br><span class="line"><span class="keyword">import</span> &#123;combineReducers&#125; <span class="keyword">from</span> <span class="string">'redux'</span></span><br><span class="line"><span class="keyword">import</span> &#123;routerReducer <span class="keyword">as</span> routing&#125; <span class="keyword">from</span> <span class="string">'react-router-redux'</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> rootReducer = combineReducers(&#123;</span><br><span class="line">      routing,</span><br><span class="line">      poetry 				: <span class="built_in">require</span>(<span class="string">'./poetry'</span>).default</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> rootReducer</span><br></pre></td></tr></table></figure>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="comment">// src/reducers/poetry.js</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> * <span class="keyword">as</span> ActionTypes <span class="keyword">from</span> <span class="string">'../actions'</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> (state = &#123;</span><br><span class="line">	fetching:<span class="literal">false</span>,</span><br><span class="line">	error:<span class="literal">false</span>,</span><br><span class="line">	errMsg:<span class="string">''</span>,</span><br><span class="line">	data:[]</span><br><span class="line">&#125;,action) =&gt; &#123;</span><br><span class="line">	<span class="keyword">if</span>(action.type === ActionTypes.FETCH_POETRY_REQUEST)&#123;</span><br><span class="line">		<span class="keyword">return</span> <span class="built_in">Object</span>.assign(&#123;...state,<span class="attr">fetching</span>:<span class="literal">true</span>,<span class="attr">errMsg</span>:<span class="string">''</span>&#125;)</span><br><span class="line">	&#125;<span class="keyword">else</span> <span class="keyword">if</span>(action.type === ActionTypes.FETCH_POETRY_SUCCESS)&#123;</span><br><span class="line">		<span class="keyword">const</span> data = action.payload.data</span><br><span class="line">		<span class="keyword">return</span> <span class="built_in">Object</span>.assign(&#123;...state,<span class="attr">fetching</span>:<span class="literal">false</span>,data,<span class="attr">errMsg</span>:<span class="string">''</span>&#125;)</span><br><span class="line">	&#125;<span class="keyword">else</span> <span class="keyword">if</span>(action.type === ActionTypes.FETCH_POETRY_FAILURE)&#123;</span><br><span class="line">		<span class="keyword">return</span> <span class="built_in">Object</span>.assign(&#123;...state,<span class="attr">fetching</span>:<span class="literal">false</span>,<span class="attr">error</span>:<span class="literal">true</span>,<span class="attr">errMsg</span>:action.payload.errMsg&#125;)</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">return</span> state</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="6-3-处理action"><a href="#6-3-处理action" class="headerlink" title="6.3 处理action"></a>6.3 处理action</h3><figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="comment">// src/action/index.js</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> &#123; createAction &#125; <span class="keyword">from</span> <span class="string">'redux-actions'</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">const</span> COMMON_FETCHING = <span class="string">'COMMON_FETCHING'</span></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">const</span> COMMON_OVER = <span class="string">'COMMON_OVER'</span></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">const</span> MSG_SHOW = <span class="string">'MSG_SHOW'</span></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">const</span> MSG_INIT = <span class="string">'MSG_INIT'</span></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">const</span> POP_LOGIN = <span class="string">'POP_LOGIN'</span></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">const</span> initMsg = <span class="function"><span class="params">()</span> =&gt;</span> (&#123;<span class="attr">type</span> : MSG_INIT&#125;)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">// 相比用thunk多了一步 多了个action 来触发saga woker</span></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">const</span> FETCH_POETRY_REQUEST = <span class="string">'FETCH_POETRY_REQUEST'</span></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">const</span> FETCH_POETRY_SUCCESS = <span class="string">'FETCH_POETRY_SUCCESS'</span></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">const</span> FETCH_POETRY_FAILURE = <span class="string">'FETCH_POETRY_FAILURE'</span></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">const</span> fetchPoetryRequest = createAction(FETCH_POETRY_REQUEST)</span><br><span class="line"><span class="keyword">export</span> <span class="keyword">const</span> fetchPoetrySuccess = createAction(FETCH_POETRY_SUCCESS)</span><br><span class="line"><span class="keyword">export</span> <span class="keyword">const</span> fetchPoetryFauilure= createAction(FETCH_POETRY_FAILURE)</span><br></pre></td></tr></table></figure>
<h3 id="6-4-处理sagas"><a href="#6-4-处理sagas" class="headerlink" title="6.4 处理sagas"></a>6.4 处理sagas</h3><figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment">// src/sagas/index.js</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> &#123; all &#125; <span class="keyword">from</span> <span class="string">'redux-saga/effects'</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> <span class="function"><span class="keyword">function</span>* <span class="title">rootSaga</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">yield</span> all([</span><br><span class="line">        ...require(<span class="string">'./fetchPoetry'</span>).default</span><br><span class="line">    ])</span><br><span class="line">  &#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment">// src/fetchPoetry.js</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> &#123;put,take,call,fork,takeEvery,select&#125; <span class="keyword">from</span> <span class="string">'redux-saga/effects'</span></span><br><span class="line"><span class="keyword">import</span> &#123;delay&#125; <span class="keyword">from</span> <span class="string">'redux-saga'</span></span><br><span class="line"><span class="keyword">import</span>  * <span class="keyword">as</span> api  <span class="keyword">from</span> <span class="string">'../api'</span></span><br><span class="line"><span class="keyword">import</span> * <span class="keyword">as</span> actionTypes <span class="keyword">from</span> <span class="string">'../actions/'</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// saga worker 监听FETCH_POETRY_REQUEST动作触发执行相应操作</span></span><br><span class="line"><span class="function"><span class="keyword">function</span>* <span class="title">fetchPoetrySaga</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    <span class="comment">// yield delay(100)</span></span><br><span class="line">    <span class="comment">// ======== 写法一 ========= </span></span><br><span class="line">    <span class="comment">// yield takeEvery(actionTypes.FETCH_POETRY_REQUEST,function*(action)&#123;</span></span><br><span class="line">    <span class="comment">//     // 调用this.props.fetchPoetryRequest(&#123;user:'poetries',age:23&#125;) 传参进来这里</span></span><br><span class="line">    <span class="comment">//     // 也可以通过这样获取state中的参数 const state = yield select()</span></span><br><span class="line">    <span class="comment">//     const &#123;user,age&#125; = action</span></span><br><span class="line">    <span class="comment">//     try&#123;</span></span><br><span class="line">    <span class="comment">//         const data =  yield call(api.get(&#123;</span></span><br><span class="line">    <span class="comment">//             url:'/mock/5b7fd63f719c7b7241f4e2fa/tangshi/tang-shi'</span></span><br><span class="line">    <span class="comment">//         &#125;))</span></span><br><span class="line">    <span class="comment">//         yield put(actionTypes.fetchPoetrySuccess(&#123;data:data.data.data&#125;))</span></span><br><span class="line">    <span class="comment">//     &#125;catch(error)&#123;</span></span><br><span class="line">    <span class="comment">//         yield put(actionTypes.fetchPoetryFauilure(&#123;errMsg:error.message&#125;))</span></span><br><span class="line">    <span class="comment">//     &#125;</span></span><br><span class="line">     </span><br><span class="line">    <span class="comment">// &#125;)</span></span><br><span class="line">    <span class="comment">// === 写法二====</span></span><br><span class="line">  <span class="keyword">while</span>(<span class="literal">true</span>)&#123;</span><br><span class="line">      <span class="comment">// 当dispatch(&#123;type:FETCH_POETRY_REQUEST&#125;)的时候被这里监听 执行对应的请求</span></span><br><span class="line">    <span class="keyword">const</span> &#123;user,age&#125; =  <span class="keyword">yield</span> take(actionTypes.FETCH_POETRY_REQUEST)</span><br><span class="line">    <span class="keyword">try</span>&#123;</span><br><span class="line">         <span class="keyword">const</span> data =  <span class="keyword">yield</span> call(api.get(&#123;</span><br><span class="line">             url:<span class="string">'/mock/5b7fd63f719c7b7241f4e2fa/tangshi/tang-shi'</span></span><br><span class="line">         &#125;))</span><br><span class="line">          <span class="keyword">yield</span> put(actionTypes.fetchPoetrySuccess(&#123;<span class="attr">data</span>:data.data.data&#125;))</span><br><span class="line">     &#125;<span class="keyword">catch</span>(error)&#123;</span><br><span class="line">         <span class="keyword">yield</span> put(actionTypes.fetchPoetryFauilure(&#123;<span class="attr">errMsg</span>:error.message&#125;))</span><br><span class="line">     &#125;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">&#125; </span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">// 导出所有的saga</span></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span>  [</span><br><span class="line">    fork(fetchPoetrySaga)</span><br><span class="line">]</span><br></pre></td></tr></table></figure>
<blockquote>
<p>完整代码例子 <a href="https://github.com/poetries/redux-saga-template" target="_blank" rel="noopener">https://github.com/poetries/redux-saga-template</a></p>
</blockquote>
<h2 id="七、总结"><a href="#七、总结" class="headerlink" title="七、总结"></a>七、总结</h2><blockquote>
<p><code>redux-saga</code>做为<code>redux</code>中间件的全部优点</p>
</blockquote>
<ul>
<li>统一<code>action</code>的形式，在<code>redux-saga</code>中，从<code>UI</code>中<code>dispatch</code>的<code>action</code>为原始对象</li>
<li>集中处理异步等存在副作用的逻辑</li>
<li>通过转化<code>effects</code>函数，可以方便进行单元测试</li>
<li>完善和严谨的流程控制，可以较为清晰的控制复杂的逻辑</li>
</ul>

      </div>
    
  </div>

</article>

<button class="assist-btn2 circle" id="assist_btn2" title="点亮屏幕" style="left: 27px; top: 152px;">
  <i class="iconfont" style="display:inline-block;color:red;width:20px;height:20px;">&#xe61d;</i>
</button>
<button class="assist-btn1 circle" id="assist_btn1" title="关闭屏幕亮度" style="left: 27px; top: 152px;">
  <i class="iconfont toc-title" style="display:inline-block;color:red;width:20px;height:20px;">&#xe61d;</i>
</button>


<script src="//cdn.bootcss.com/jquery/3.1.1/jquery.min.js"></script>	

<script src="https://my.openwrite.cn/js/readmore.js" type="text/javascript"></script>
<script>
  const btw = new BTWPlugin();
  btw.init({
    id: "container",
    blogId: "22699-1592137983091-414",
    name: "前端进阶之旅",
    qrcode: "https://poetries1.gitee.io/img-repo/2020/06/qrcode.jpg",
    keyword: "3a3b3c",
  });
</script>

<script type="text/javascript">

// white theme
var body = {color: "#555", background: "#000"};
var a_tag = {color: "#222"};
var header = { background: "#222"};
var logo_line_i = {background: "#222"};
// var post_code = {background: "#eee", color: "#222"};

function switch_theme() {
 $("body").css(body);
 $("a:not('.links-of-author-item a, .site-state-item a, .site-state-posts a, .feed-link a, .motion-element a, .post-tags a, .show-commit-cls a, #donate_board a')").css(a_tag);
 $(".header, .footer").css(header);
 $(".logo-line-before i, .logo-line-after i").css(logo_line_i);
 //$(".post code").css(post_code);
 $("#idhyt-surprise-ball #idhyt-surprise-ball-animation .drag").css(a_tag);
 $(".post-title-link, .posts-expand .post-meta, .post-comments-count, .disqus-comment-count, .post-category a, .post-nav-next a, .post-nav-item a").css(a_tag);
 
 // $("code").css({color: '#c5c8c6', background: '#1d1f21'});
 //$("#assist_btn1").hide(1500);
}

$(function () {
$("#assist_btn2").css("display","none");
 $("#assist_btn1").click(function() {
     switch_theme();
$("div#toc.toc-article").css({
 "background":"#eaeaea",
 "opacity":1
});
$(".toc-article ol").show();
$("#toc.toc-article .toc-title").css("color","#a98602");
$("#assist_btn1").css("display","none");
$("#assist_btn2").css("display","block");
 });
$("#assist_btn2").click(function() {
$("#assist_btn2").css("display","none");
$("#assist_btn1").css("display","block");
$("body").css("background","url(http://www.miaov.com/static/ie/images/news/bg.png)")
     $(".header, .footer").css("background","url(http://www.miaov.com/static/ie/images/news/bg.png)")
$(".toc-article ol").toggle(1000);
 });
});


//背景随机

var Y, O, E, L, B, C, T, z, N, S, A, I;
!function() {
var e = function() {
for (O.clearRect(0, 0, L, B), T = [{
x: 0,
y: .7 * B + C
}, {
x: 0,
y: .7 * B - C
}]; T[1].x < L + C;) t(T[0], T[1])
}, t = function(e, t) {
O.beginPath(), O.moveTo(e.x, e.y), O.lineTo(t.x, t.y);
var n = t.x + (2 * I() - .25) * C,
 r = a(t.y);
O.lineTo(n, r), O.closePath(), N -= S / -50, O.fillStyle = "#" + (127 * A(N) + 128 << 16 | 127 * A(N + S / 3) + 128 << 8 | 127 * A(N + S / 3 * 2) + 128).toString(16), O.fill(), T[0] = T[1], T[1] = {
 x: n,
 y: r
}
}, a = function n(e) {
var t = e + (2 * I() - 1.1) * C;
return t > B || t < 0 ? n(e) : t
};
Y = document.getElementById("evanyou"), O = Y.getContext("2d"), E = window.devicePixelRatio || 1, L = window.innerWidth, B = window.innerHeight, C = 90, z = Math, N = 0, S = 2 * z.PI, A = z.cos, I = z.random, Y.width = L * E, Y.height = B * E, O.scale(E, E), O.globalAlpha = .6, document.onclick = e, document.ontouchstart = e, e()
}()

   
$("#toc-eye").click(function(){
$("#toc.toc-article").toggle(1000);
});

</script>


   
  <div class="text-center donation">
    <div class="inner-donation">
      <span class="btn-donation">支持一下</span>
      <div class="donation-body">
        <div class="tip text-center">扫一扫，支持poetries</div>
        <ul>
        
          <li class="item">
            
              <span>微信扫一扫</span>
            
            <img src="/images/weixin.jpg" alt="">
          </li>
        
          <li class="item">
            
              <span>支付宝扫一扫</span>
            
            <img src="/images/zhifubao.jpg" alt="">
          </li>
        
        </ul>
      </div>
    </div>
  </div>


   
  <div class="box-prev-next clearfix">
    <a class="show pull-left" href="/2018/08/29/vue-vuex/">
        <i class="icon icon-angle-left"></i>
    </a>
    <a class="show pull-right" href="/2018/08/31/acq-mobx/">
        <i class="icon icon-angle-right"></i>
    </a>
  </div>




</div>


  <a id="backTop" class="back-top">
    <i class="icon-angle-up"></i>
  </a>




  <div class="modal" id="modal">
  <span id="cover" class="cover hide"></span>
  <div id="modal-dialog" class="modal-dialog hide-dialog">
    <div class="modal-header">
      <span id="close" class="btn-close">关闭</span>
    </div>
    <hr>
    <div class="modal-body">
      <ul class="list-toolbox">
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/archives/"
              rel="noopener noreferrer"
              target="_self"
              >
              博客
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/categories/"
              rel="noopener noreferrer"
              target="_self"
              >
              分类
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/tags/"
              rel="noopener noreferrer"
              target="_self"
              >
              标签
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/search/"
              rel="noopener noreferrer"
              target="_self"
              >
              搜索
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/link/"
              rel="noopener noreferrer"
              target="_self"
              >
              友链
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/about/"
              rel="noopener noreferrer"
              target="_self"
              >
              关于
            </a>
          </li>
        
      </ul>

    </div>
  </div>
</div>



  
      <div class="fexo-comments comments-post">
    

    

    
    

    

    
    

    

<!-- Gitalk评论插件通用代码 -->
<div id="gitalk-container"></div>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.css">
<script src="https://cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.min.js"></script>
<script>
const gitalk = new Gitalk({
  clientID: '5567a2c4abb858009d96',
  clientSecret: 'b9039ec056cf5c2346b3cdb63308a28c163f91e5',
  repo: 'poetries.github.io',
  owner: 'poetries',
  // 在这里设置一下截取前50个字符串, 这是因为 github 对 label 的长度有了要求, 如果超过
  // 50个字符串则会报错.
  // id: location.pathname.split('/').pop().substring(0, 49),
  id: location.pathname,
  admin: ['poetries'],
  // facebook-like distraction free mode
  distractionFreeMode: false
})
gitalk.render('gitalk-container')
</script>
<!-- Gitalk代码结束 -->



  </div>

  

  <script type="text/javascript">
  function loadScript(url, callback) {
    var script = document.createElement('script')
    script.type = 'text/javascript';

    if (script.readyState) { //IE
      script.onreadystatechange = function() {
        if (script.readyState == 'loaded' ||
          script.readyState == 'complete') {
          script.onreadystatechange = null;
          callback();
        }
      };
    } else { //Others
      script.onload = function() {
        callback();
      };
    }

    script.src = url;
    document.getElementsByTagName('head')[0].appendChild(script);
  }

  window.onload = function() {
    loadScript('/js/bundle.js?235683', function() {
      // load success
    });
  }
</script>


  <!-- 页面点击小红心 -->
  <script type="text/javascript" src="/js/clicklove.js"></script>
 
  
</body>
</html>
